import type { Reducer, Effect } from 'umi';
import { getOnlineCashierid, OnlineCashier } from '@/service';
import { getParamsString } from '@/utils';

export type AppStateType = {
  cashier_id?: string;
  table_id?: any;
} & OnlineCashier;

export type AppModelType = {
  namespace: string;
  state: AppStateType;
  effects?: {
    init: Effect;
  };
  reducers?: {
    save: Reducer<AppStateType>;
  };
};

const Model: AppModelType = {
  namespace: 'app',
  state: {
    uniacid: '',
    store_id: '',
    table_id: '',
  },
  effects: {
    *init({ data }, { call, put }) {
      console.log(data);

      const uniacid = getParamsString('uniacid');
      const store_id = getParamsString('store_id');
      const table_id = getParamsString('table_id');

      const res = yield getOnlineCashierid({
        uniacid: uniacid as string,
        store_id: store_id as string,
      });

      yield put({
        type: 'save',
        data: {
          table_id,
          uniacid,
          store_id,
          cashier_id: res.data,
        },
      });
    },
  },
  reducers: {
    save(state, action) {
      if (action.data) {
        localStorage.setItem(
          'mustParams',
          JSON.stringify({
            ...action.data,
          }),
        );
      }

      return {
        ...state,
        ...action.data,
      };
    },
  },
};

export default Model;
